package com.spshiro.config;

import com.spshiro.pojo.User;
import com.spshiro.service.UserService;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @create 2022-03-2022/3/16-21:19
 */
//自定义RealMen 继承AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("给予授权 -》doGetAuthorizationInfo（PrincipalCollection）");

        //给用户授权
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        //授权
        //info.addStringPermission("u:root");//无论谁全都给

        Subject subject =SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();//获取当前正在认证的用户
        //数据库获取权限
        info.addStringPermission(currentUser.getRole());


        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("基于认证-》doGetAuthenticationInfo（AuthenticationToken）");

        //获取
        UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken)authenticationToken;
        User user=  userService.getAccount(usernamePasswordToken.getUsername());
        //账户判断
        if(user ==null)
            return null;//抛异常
        //密码判断
        //”1“，”2“，”3“：1传对象值，2传密码，
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");


    }
}
